package com.onenine.app.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;

import com.alibaba.sdk.android.manager.OssManager;
import com.chad.library.adapter.base.BaseItemDraggableAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.adapter.ImageAddAdapter;
import com.onenine.app.listener.LastItemUnDragAndSwipeCallback;
import com.onenine.app.request.ReportSubmitRequest;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.popwin.MediaPopWindow;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.SimpleToolbar;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.KeyboardUtils;
import com.onenine.common.util.SizeUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建时间：2018/6/4 0004 16:37
 * 创建人：fly
 * 功能描述：举报或问题反馈提交
 */
public class ReportSubmitActivity extends UploadImageActivity implements View.OnClickListener
        , BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    private SimpleToolbar mToolbar;
    private RecyclerView mRecyclerView;
    private BaseItemDraggableAdapter mImageAdapter;
    private EditText mEditContent;
    private String mTargetId;
    private int mObjType, mComType;

    /**
     * 举报
     *
     * @param context
     * @param complainObjType
     * @param complainType
     * @param targetId
     */
    public static void launchReportActivity(Context context, int complainObjType, int complainType, String targetId) {
        Intent intent = new Intent(context, ReportSubmitActivity.class);
        intent.putExtra("complainObjType", complainObjType);
        intent.putExtra("complainType", complainType);
        intent.putExtra("targetId", targetId);
        context.startActivity(intent);
    }

    /**
     * 意见反馈
     *
     * @param context
     */
    public static void launchSuggestionActivity(Context context) {
        Intent intent = new Intent(context, ReportSubmitActivity.class);
        intent.putExtra("complainObjType", DataType.REPORT_SUGGESTION);
        intent.putExtra("complainType", 5);
        intent.putExtra("targetId", "");
        context.startActivity(intent);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_report_submit;
    }

    @Override
    protected void initViews() {
        super.initViews();
        initVars();
        setTitleHint();
        initImageAdapter();
    }

    private void initVars() {
        mObjType = getIntent().getIntExtra("complainObjType", DataType.REPORT_GROUP);
        mComType = getIntent().getIntExtra("complainType", 1);
        mTargetId = getIntent().getStringExtra("targetId");
        mEditContent = findViewById(R.id.edt_content);
        mToolbar = findViewById(R.id.tb_toolbar);
        mToolbar.setRightTitle(R.string.commit);
    }

    private void setTitleHint() {
        switch (mObjType) {
            case DataType.REPORT_USER:
                mToolbar.setCenterTitle(R.string.complain_user);
                break;
            case DataType.REPORT_GROUP:
                mToolbar.setCenterTitle(R.string.complain_group);
                break;
            case DataType.REPORT_SUGGESTION:
                mToolbar.setCenterTitle(R.string.suggestion);
                mEditContent.setHint(R.string.suggestion_desc);
                break;
        }
    }

    @Override
    protected void initListeners() {
        mToolbar.setOnRightClickListener(this);
        mImageAdapter.setOnItemClickListener(this);
        mImageAdapter.setOnItemChildClickListener(this);
    }

    private void initImageAdapter() {
        mImagePaths.add(UploadImageActivity.IMAGE_ADD);
        mRecyclerView = findViewById(R.id.rv_grid);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mRecyclerView.setHasFixedSize(true);
        mImageAdapter = new ImageAddAdapter(mImagePaths, (AppConfig.SCREEN_WIDTH - SizeUtils.dp2px(58)) / 3);
        mRecyclerView.setAdapter(mImageAdapter);
        mImageAdapter.enableDragItem(new LastItemUnDragAndSwipeCallback(mRecyclerView, mImageAdapter).getItemTouchHelper());
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        mImageAdapter.remove(position);
        mRecyclerView.requestLayout();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (position == mImagePaths.size() - 1) {
            KeyboardUtils.hideSoftInput(ReportSubmitActivity.this);
            new MediaPopWindow(ReportSubmitActivity.this
                    , ReportSubmitActivity.this).showPopWindow();
        } else if (position >= 0) {
            ArrayList<String> urls = new ArrayList<>(mImageAdapter.getData());
            urls.remove(urls.size() - 1);
            BrowserImageActivity.launchActivity(this, urls, position);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right_title:
                if (mEditContent.getText().toString().trim().length() == 0) {
                    Toasty.showNormal(mEditContent.getHint());
                    return;
                }
                if (mObjType != DataType.REPORT_SUGGESTION && mImagePaths.size() <= 1) {
                    Toasty.showNormal(R.string.chat_complain_proof);
                    return;
                }
                if (!isImageCompressed()) {
                    Toasty.showNormal(R.string.wait_for_image_compress);
                    return;
                }
                showLoading(R.string.upload_image_doing);
                List<String> uploadList = new ArrayList<>();
                uploadList.addAll(mImagePaths.subList(0, mImagePaths.size() - 1));
                mRecyclerView.setTag(R.id.data_tag, uploadList);
                OssManager.getInstance(ApUtils.getApp()).ossUpload(uploadList, new ArrayList<String>(), this);
                break;
        }
    }

    @Override
    protected void uploadImagesSuccess(String imageUrls) {
        mRecyclerView.setTag(R.id.data_tag, null);
        submitData(imageUrls);
    }

    /**
     * 提交数据
     *
     * @param imageUrls
     */
    private void submitData(String imageUrls) {
        ReportSubmitRequest request = new ReportSubmitRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setTargetUserId(mTargetId);
        request.setReportDesc(mEditContent.getText().toString().trim());
        request.setReportObjType(mObjType);
        request.setReportType(mComType);
        request.setReportPicUrl(imageUrls);
        OkRequest.getInstance().withUrl(UrlConfig.SEND_COMPLAIN)
                .withRequest(request).doRequest(ReportSubmitActivity.class.getSimpleName()
                , new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        dismissLoading();
                        if (response.isSuccess()) {
                            Toasty.showNormal(R.string.submit_success);
                            finish();
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    @Override
    protected void compressImageSuccess(File file) {
        mImageAdapter.notifyItemInserted(0);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkRequest.getInstance().cancelTag(ReportSubmitActivity.class.getSimpleName());
        Object obj = mRecyclerView.getTag(R.id.data_tag);
        if (obj != null) {
            OssManager.getInstance(ApUtils.getApp())
                    .cancelAsyncTask(obj.toString());
        }
    }

}
